<?php

namespace support;

use app\services\ConfigService;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class QiNiuStore
{
    protected $accessKey;
    protected $secretKey;

    protected $bucketName;

    protected $auth;

    protected $config;

    public function __construct()
    {
        $this->config = $config = ConfigService::getByGroup('qiniu');

        if (empty($config) || empty($config['qiniu_ak']) || empty($config['qiniu_sk']) || empty($config['qiniu_bn']) || empty($config['qiniu_url'])) {
            throw new \Exception('请在后台配置七牛云');
        }

        $this->accessKey = $config['qiniu_ak'];
        $this->secretKey = $config['qiniu_sk'];
        $this->bucketName = $config['qiniu_bn'];

        $this->auth = new Auth($this->accessKey, $this->secretKey);
    }

    public function upload(Request $request, $allowedExtensions=['jpg', 'jpeg', 'png', 'gif', 'fjr', 'd4', 'r20', 'xml'])
    {
        $file = $request->file('file');

        $extension = strtolower($file->getUploadExtension());

        if (!in_array($extension, $allowedExtensions)) {
            return err_rsp('不正确的文件扩展');
        }

        $fileName = 'userUpload/' . microtime(true) * 1000 . '.' . $extension;
        $relativePath = '/' . $fileName;
        $absolutePath = public_path() . $relativePath;
        $file->move($absolutePath);

        list($ret, $err) = $this->uploadLocalToRemote($absolutePath, $fileName);

        if (empty($err)) {
            return $this->config['qiniu_url'] . $ret['key'];
        } else {
            throw new \Exception('上传失败');
        }
    }

    public function uploadLocalToRemote($localPath, $remotePath)
    {
        $token = $this->auth->uploadToken($this->bucketName);

        $uploadMgr = new UploadManager();

        list($ret, $err) = $uploadMgr->putFile($token, $remotePath, $localPath);

        return [$ret, $err];
    }
}